package com.hiss.basic.system.utlis;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hiss.basic.model.system.enums.MenuComponentTypeEnum;
import com.hiss.basic.model.system.response.SysMenuQueryTreeResponse;
import com.hiss.basic.model.system.response.route.RouteMeta;
import com.hiss.basic.model.system.response.route.RouteResponse;
import com.hiss.basic.starter.core.constant.SystemConstant;
import com.hiss.basic.starter.core.utils.tree.TreeNode;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.List;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RouteUtils {

    public static List<RouteResponse> buildRouteTree(List<TreeNode<Long, Integer>> treeList) {
        if (CollectionUtil.isNotEmpty(treeList)) {
            List<RouteResponse> routeList = ListUtil.toList();

            for (TreeNode<Long, Integer> treeNode : treeList) {
                SysMenuQueryTreeResponse node = (SysMenuQueryTreeResponse) treeNode;

                RouteResponse route = new RouteResponse();
                route.setName(node.getName());
                route.setPath(node.getPath());
                route.setComponent(node.getComponent());

                RouteMeta meta = new RouteMeta();
                meta.setTitle(node.getTitle());
                meta.setIcon(node.getIcon());
                meta.setOrder(node.getSort());
                meta.setKeepAlive(ObjectUtil.equal(1, node.getCacheStatus()));
                meta.setHideInMenu(ObjectUtil.equal(1, node.getHiddenStatus()));

                if (ObjectUtil.equal(MenuComponentTypeEnum.IFRAME.getCode(), node.getComponentType())) {
                    route.setComponent(SystemConstant.LINK_COMPONENT);
                    meta.setIframeSrc(node.getLink());
                } else if (ObjectUtil.equal(MenuComponentTypeEnum.LINK.getCode(), node.getComponentType())) {
                    route.setComponent(SystemConstant.LINK_COMPONENT);
                    meta.setLink(node.getLink());
                } else {
                    route.setComponent(node.getComponent());
                }
                route.setMeta(meta);

                if (CollectionUtil.isNotEmpty(node.getChildren())) {
                    route.setChildren(buildRouteTree(node.getChildren()));
                }

                routeList.add(route);
            }
            return routeList;
        }
        return ListUtil.toList();
    }
}
